﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.sale
{
    public partial class saleplan_add : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty = "0";

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty");

            DataTable dtData = ((saleplan_product_class)Session["saleplan_product"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty"] = dr["qty"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        private void Reset()
        {
            uc_from_years.Reset();
            uc_from_months.Reset();

            uc_from_product.clearValue();

            txt_qty.Text = "";

            ((saleplan_product_class)Session["saleplan_product"]).Reset();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    ((saleplan_product_class)Session["saleplan_product"]).Reset();
                }
                catch
                {
                    Session.Add("saleplan_product", new saleplan_product_class(Session["connectionString"].ToString()));
                }

                Bind();

                Total_qty = ((saleplan_product_class)Session["saleplan_product"]).Total_qty.ToString();
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            
            alert_msg = "";

            edowork.com.Model.saleplanInfo saleplanInfo = new saleplanInfo();
            edowork.com.Model.saleplandetailInfo saleplandetailInfo = new saleplandetailInfo();

            saleplanInfo.Years = uc_from_years.getValue();
            saleplanInfo.Quarter = "";
            saleplanInfo.Month = uc_from_months.getValue();

            saleplanInfo.Userid = Session["userid"].ToString();
            saleplanInfo.Sysdate = DateTime.Now.ToString("yyyy-MM-dd");

            saleplanInfo.Remark = txt_remark.Text.Trim();
            saleplanInfo.M_stu = "0";
            saleplanInfo.M_date = "";
            saleplanInfo.M_id = "";

            if (String.IsNullOrEmpty(saleplanInfo.Years))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择所在年份");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(saleplanInfo.Month))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择所在月份");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (((saleplan_product_class)Session["saleplan_product"]).getListTotal() <= 0)
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入销售的货品信息");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            //取得采购计划单编码
            saleplanInfo.Sepid = SysID.SCR_SaleplanID(Session["connectionString"].ToString(), ref alert_msg);
            saleplandetailInfo.Sepid = saleplanInfo.Sepid;

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;
                DataSet dsResult = null;

                //检查saleplan表中是否已存在同年份，同月份的采购计划
                sql = String.Format("select * from saleplan where years='{0}' and month='{1}' and userid='{2}'", saleplanInfo.Years, saleplanInfo.Month, saleplanInfo.Userid);

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "已存在相同月份的采购计划");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", saleplanInfo.Years, saleplanInfo.Month);

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //保存入saleplanInfo表
                sql = String.Format(saleplanInfo.SQL_Insert(), saleplanInfo.Sepid, saleplanInfo.Years, saleplanInfo.Quarter, saleplanInfo.Month,
                                                               saleplanInfo.Userid, saleplanInfo.Sysdate, saleplanInfo.Remark, saleplanInfo.M_stu,
                                                               saleplanInfo.M_date, saleplanInfo.M_id);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                DataTable dtData = ((saleplan_product_class)Session["saleplan_product"]).getList().Copy();

                foreach (DataRow dr in dtData.Rows)
                {
                    //保存入saleplandetail表
                    sql = String.Format(saleplandetailInfo.SQL_Insert(), saleplandetailInfo.Sepid,
                                        dr["productcode"].ToString(), dr["qty"].ToString(), "0");

                    result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                    if (result <= 0)
                    {
                        tran.Rollback();
                        tranutil.CloseConnection();

                        alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        return;
                    }
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            Reset();

            Bind();

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //重置
        protected void btnReset_Click(object sender, EventArgs e)
        {
            Reset();

            Bind();
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string url = "/system/sale/saleplan.aspx";

            Response.Redirect(url);
        }

        //添加货品
        protected void btAddproduct_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            string productu_code = uc_from_product.getValue();
            string qty = txt_qty.Text.Trim();

            if (((saleplan_product_class)Session["saleplan_product"]).Add(productu_code, qty, ref alert_msg) == false)
            {
                alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            uc_from_product.clearValue();
            txt_qty.Text = "";

            Bind();

            Total_qty = ((saleplan_product_class)Session["saleplan_product"]).Total_qty.ToString();
        }

        //删除货品
        protected void rplist_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "Delete":
                    {
                        ((saleplan_product_class)Session["saleplan_product"]).Delect(id);

                        //查询
                        Bind();

                        Total_qty = ((saleplan_product_class)Session["saleplan_product"]).Total_qty.ToString();

                        alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Delete);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);


                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
    }
}